import cv2
import numpy as np
import HandTrackingModule as htm
import time
import os
import math

def hex_to_bgr(hex_color):
    """将十六进制颜色（如 #FF3131）转换为 OpenCV 的 BGR 元组"""
    hex_color = hex_color.lstrip('#')  # 去掉 #
    r = int(hex_color[0:2], 16)
    g = int(hex_color[2:4], 16)
    b = int(hex_color[4:6], 16)
    return (b, g, r)  # OpenCV 是 BGR 顺序！

brushThickness = 15
eraserThickness = 100
folerPath = 'VirtualPainterBackground'
myList = os.listdir(folerPath)
overlayList = []
for imgPath in myList:
    image = cv2.imread(f'{folerPath}/{imgPath}')
    overlayList.append(image)

header = overlayList[6]
drawColor = (255, 0, 255)

# cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)

detector = htm.handDetector(detectionCon=0.65)
xp = 0
yp = 0
imgCanvas = np.zeros((720, 1280, 3), np.uint8)

while True:
    # 1. import image

    success, img = cap.read()
    img = cv2.flip(img, 1)

    # 2. find hand Landmarks
    img = detector.findHands(img)
    lmList = detector.findPosition(img, draw=False)
    if len(lmList) != 0:
        
        # tip of index and middle finger
        x1 ,y1 = lmList[8][1:]
        
        # thumb finger
        x3 ,y3 = lmList[4][1:]
        
        # 3. Check which fingers are up
        fingers = detector.fingersUp(thumbLeft= True)
        # print(fingers)

        # 4.If Selected mode - Two fingers are up
        if fingers[0] and not any(fingers[1:5]):
            xp, yp = 0, 0
            # print("Selected")
            # Checking for the click
            if x3 < 180:
                if 110 < y3 < 210:
                    header = overlayList[0]
                    drawColor = hex_to_bgr("#000000FF")
                elif 210 < y3 < 304:
                    header = overlayList[1]
                    drawColor = hex_to_bgr("#FFFFFFFF")
                elif 304 < y3 < 400:
                    header = overlayList[2]
                    drawColor = hex_to_bgr("#FF3131FF")
                elif 400 < y3 < 494:
                    header = overlayList[3]
                    drawColor = hex_to_bgr("#00BF63")
                elif 494 < y3 < 592:
                    header = overlayList[4]
                    drawColor = hex_to_bgr("#0081CC")
                elif y3 > 600:
                    header = overlayList[5]
                    drawColor = hex_to_bgr("#000000FF")
            cv2.circle(img, (x3, y3), 15, drawColor, cv2.FILLED)
        # 5. If Drawing mode - Index finger is up
        elif fingers[1] and not any(fingers[2:5]) and not fingers[0]:
            if xp == 0 and yp == 0:
                xp, yp = x1, y1
            if (xp - x1)**2 + (yp - y1)**2 > 75**2:
                xp, yp = x1, y1
            if drawColor == hex_to_bgr("#000000FF"):
                cv2.line(img, (xp, yp), (x1, y1), drawColor, eraserThickness)
                cv2.line(imgCanvas, (xp, yp), (x1, y1), drawColor, eraserThickness)
                # print("Erasing")
            else:
                cv2.line(img, (xp, yp), (x1, y1), drawColor, brushThickness)
                cv2.line(imgCanvas, (xp, yp), (x1, y1), drawColor, brushThickness)
                # print("Drawing")

            cv2.circle(img, (x1, y1), 15, drawColor, cv2.FILLED) 
            xp, yp = x1, y1
        else:
            pass
    
    imgGray = cv2.cvtColor(imgCanvas, cv2.COLOR_BGR2GRAY)
    _, imgInv = cv2.threshold(imgGray, 50, 255, cv2.THRESH_BINARY_INV)
    imgInv = cv2.cvtColor(imgInv, cv2.COLOR_GRAY2BGR)
    img = cv2.bitwise_and(img, imgInv)
    img = cv2.bitwise_or(img, imgCanvas)

    if success:
        # set header
        img[0:720,0:180] = header
        cv2.imshow('img', img)
        # cv2.imshow('imgCanvas', imgCanvas)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break